package archer.framework.web.filter;

import archer.framework.core.lang.net.IpList;
import archer.framework.utils.ServletUtils;

import static archer.framework.utils.ValidateUtils.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import java.io.IOException;

/**
 * ip过滤器
 *
 * @author kent
 * @date 16/7/6.
 */
public class IpFilter implements Filter {

    private static Logger logger = LoggerFactory.getLogger(IpFilter.class);

    //----------------------to be override------------------------------

    public IpList getWhiteList() {
        return null;
    }

    public IpList getBlackList() {
        return null;
    }

    protected void accessDenied(ServletRequest servletRequest, ServletResponse servletResponse) {
        //empty here
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        IpList whiteList = getWhiteList();
        IpList blackList = getBlackList();

        // 黑名单的拒绝访问
        if (isNotEmpty(blackList) && blackList.contains(getClientIP(servletRequest))) {
            logAccessDeniedIp(getClientIP(servletRequest));
            accessDenied(servletRequest, servletResponse);
            return;
        }

        // 不在白名单拒绝访问
        if (isNotEmpty(whiteList) && !whiteList.contains(getClientIP(servletRequest))) {
            logAccessDeniedIp(getClientIP(servletRequest));
            accessDenied(servletRequest, servletResponse);
            return;
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // empty
    }

    @Override
    public void destroy() {
        // empty
    }

    //------------------------------------ private ----------------------------------------

    // 初始化参数名称
    private static final String WHITE_PATTERN = "whitePattern";
    private static final String BLACK_PATTERN = "blackPattern";

    protected IpList getWhiteListFromInitParam(FilterConfig filterConfig) {
        String ipList = isEmpty(filterConfig.getInitParameter(WHITE_PATTERN))
                ? "127.0.0.1"
                : filterConfig.getInitParameter(WHITE_PATTERN);
        return IpList.create(ipList);
    }

    protected IpList getBlackListFromInitParam(FilterConfig filterConfig) {
        String ipList = filterConfig.getInitParameter(BLACK_PATTERN);
        return IpList.create(ipList);
    }

    protected String getClientIP(ServletRequest servletRequest) {
        return ServletUtils.getClientIp(servletRequest);
    }

    protected void logAccessDeniedIp(String ip) {
        logger.info(">>>>>>>>>>>>>>ip[" + ip + "] 访问被拒绝");
    }
}
